package com.example.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpHeaders;
import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getCookie")
    //可以使用StringBuilder把所有内容打印出来
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        if(cookies !=null){
            for(Cookie ck:cookies){
                System.out.println(ck.getValue());
            }
        }
        return "success";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name){
        return name;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        //有则获取，无则创建
        HttpSession session=request.getSession();
        session.setAttribute("name","lisi");
        return "set Session successfully";
    }

    @RequestMapping("/getSession")
    public String getSession(@SessionAttribute("name") String name){
        return "从Session中获取name:"+name;
    }

    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String name=(String)session.getAttribute("name");
        return "从Session中获取name:"+name;
    }

    @RequestMapping("/getSession3")
    public String getSession3(HttpServletRequest request){
        HttpSession session=request.getSession();
        String name=(String)session.getAttribute("name");
        return "从Session中获取name:"+name;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return userAgent;
    }


}
